<template>
  <div class="customer-analytics">
    <!-- 客户概览 -->
    <div class="overview-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="item in overviewData" :key="item.title">
          <el-card class="overview-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon" :style="{ backgroundColor: item.color }">
                <el-icon :size="20">
                  <component :is="item.icon" />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-value">{{ item.value }}</div>
                <div class="card-trend" :class="item.trend > 0 ? 'positive' : 'negative'">
                  <el-icon size="12">
                    <ArrowUp v-if="item.trend > 0" />
                    <ArrowDown v-else />
                  </el-icon>
                  {{ Math.abs(item.trend) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表分析 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 客户增长趋势 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">客户增长趋势</span>
                <el-select v-model="growthPeriod" size="small" style="width: 120px">
                  <el-option label="最近7天" value="7d" />
                  <el-option label="最近30天" value="30d" />
                  <el-option label="最近90天" value="90d" />
                </el-select>
              </div>
            </template>
            <div ref="customerGrowthChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 客户等级分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">客户等级分布</span>
            </template>
            <div ref="customerLevelChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 客户活跃度 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">客户活跃度分析</span>
            </template>
            <div ref="customerActivityChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 客户价值分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">客户价值分布</span>
            </template>
            <div ref="customerValueChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 客户地区分布热力图 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">客户地区分布热力图</span>
            </template>
            <div ref="customerMapChart" class="chart-container" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 客户数据表格 -->
    <div class="data-section">
      <el-row :gutter="20">
        <!-- 新增客户 -->
        <el-col :xs="24" :lg="12">
          <el-card class="table-card">
            <template #header>
              <span class="card-title">最新客户</span>
            </template>
            <el-table :data="newCustomers" stripe>
              <el-table-column prop="name" label="客户名称" />
              <el-table-column prop="level" label="等级" width="80">
                <template #default="{ row }">
                  <el-tag :type="getLevelType(row.level)" size="small">
                    {{ getLevelLabel(row.level) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="registerTime" label="注册时间" width="120">
                <template #default="{ row }">
                  {{ formatDate(row.registerTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 活跃客户 -->
        <el-col :xs="24" :lg="12">
          <el-card class="table-card">
            <template #header>
              <span class="card-title">活跃客户</span>
            </template>
            <el-table :data="activeCustomers" stripe>
              <el-table-column prop="name" label="客户名称" />
              <el-table-column prop="orders" label="订单数" width="80" align="right" />
              <el-table-column prop="lastOrderTime" label="最后下单" width="120">
                <template #default="{ row }">
                  {{ formatDate(row.lastOrderTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { User, UserFilled, TrendCharts, Money, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { formatDate, getLevelLabel } from '@/utils'

// 图表实例
const customerGrowthChart = ref<HTMLElement>()
const customerLevelChart = ref<HTMLElement>()
const customerActivityChart = ref<HTMLElement>()
const customerValueChart = ref<HTMLElement>()
const customerMapChart = ref<HTMLElement>()

let customerGrowthChartInstance: echarts.ECharts
let customerLevelChartInstance: echarts.ECharts
let customerActivityChartInstance: echarts.ECharts
let customerValueChartInstance: echarts.ECharts
let customerMapChartInstance: echarts.ECharts

// 数据
const growthPeriod = ref('30d')

// 基础客户概览数据
const baseOverviewData = [
  {
    title: '总客户数',
    value: '1,234',
    trend: 12.5,
    icon: 'User',
    color: '#409EFF',
  },
  {
    title: '新增客户',
    value: '156',
    trend: 8.2,
    icon: 'UserFilled',
    color: '#67C23A',
  },
  {
    title: '活跃客户',
    value: '892',
    trend: -2.1,
    icon: 'TrendCharts',
    color: '#E6A23C',
  },
  {
    title: '客户价值',
    value: '¥2.3M',
    trend: 15.3,
    icon: 'Money',
    color: '#F56C6C',
  },
]

// 动态客户概览数据
const overviewData = ref([...baseOverviewData])

/**
 * 生成客户增长趋势数据
 */
const generateGrowthTrendData = () => {
  const baseData = {
    '7d': {
      xAxisData: ['1天前', '2天前', '3天前', '4天前', '5天前', '6天前', '7天前'],
      newCustomers: [12, 15, 8, 18, 22, 16, 14],
      totalCustomers: [1234, 1222, 1207, 1199, 1181, 1159, 1143]
    },
    '30d': {
      xAxisData: ['第1周', '第2周', '第3周', '第4周'],
      newCustomers: [89, 76, 95, 68],
      totalCustomers: [1234, 1145, 1069, 974]
    },
    '90d': {
      xAxisData: ['第1月', '第2月', '第3月'],
      newCustomers: [328, 289, 356],
      totalCustomers: [1234, 906, 617]
    }
  }
  
  return baseData[growthPeriod.value] || baseData['30d']
}

/**
 * 生成客户等级分布数据
 */
const generateLevelData = () => {
  const baseData = [
    { value: 45, name: '钻石客户' },
    { value: 135, name: '黄金客户' },
    { value: 234, name: '白银客户' },
    { value: 345, name: '青铜客户' }
  ]
  
  return baseData
}

/**
 * 生成客户活跃度数据
 */
const generateActivityData = () => {
  const baseData = {
    categories: ['非常活跃', '活跃', '一般', '不活跃', '流失'],
    values: [156, 234, 189, 98, 45]
  }
  
  return baseData
}

/**
 * 生成客户价值分布数据
 */
const generateValueData = () => {
  const baseData = [
    { value: 45, name: '高价值客户' },
    { value: 35, name: '中价值客户' },
    { value: 20, name: '低价值客户' }
  ]
  
  return baseData
}

/**
 * 更新所有图表
 */
const updateCharts = () => {
  if (customerGrowthChartInstance) {
    const trendData = generateGrowthTrendData()
    customerGrowthChartInstance.setOption({
      xAxis: { data: trendData.xAxisData },
      series: [
        { data: trendData.newCustomers },
        { data: trendData.totalCustomers }
      ]
    })
  }
  
  if (customerLevelChartInstance) {
    const levelData = generateLevelData()
    customerLevelChartInstance.setOption({
      series: [{ data: levelData }]
    })
  }
  
  if (customerActivityChartInstance) {
    const activityData = generateActivityData()
    customerActivityChartInstance.setOption({
      xAxis: { data: activityData.categories },
      series: [{ data: activityData.values }]
    })
  }
  
  if (customerValueChartInstance) {
    const valueData = generateValueData()
    customerValueChartInstance.setOption({
      series: [{ data: valueData }]
    })
  }
}

// 新增客户数据
const newCustomers = ref([
  { name: '上海纺织公司', level: 'gold', registerTime: '2024-12-20T10:30:00.000Z' },
  { name: '北京服装厂', level: 'silver', registerTime: '2024-12-19T14:20:00.000Z' },
  { name: '广州制衣企业', level: 'bronze', registerTime: '2024-12-18T09:15:00.000Z' },
  { name: '深圳时装公司', level: 'diamond', registerTime: '2024-12-17T16:45:00.000Z' },
  { name: '杭州丝绸厂', level: 'gold', registerTime: '2024-12-16T11:30:00.000Z' },
])

// 活跃客户数据
const activeCustomers = ref([
  { name: '上海时装有限公司', orders: 45, lastOrderTime: '2024-12-20T15:30:00.000Z' },
  { name: '北京服饰集团', orders: 38, lastOrderTime: '2024-12-19T10:20:00.000Z' },
  { name: '广州纺织厂', orders: 32, lastOrderTime: '2024-12-18T14:15:00.000Z' },
  { name: '深圳制衣公司', orders: 28, lastOrderTime: '2024-12-17T09:45:00.000Z' },
  { name: '杭州丝绸企业', orders: 25, lastOrderTime: '2024-12-16T16:30:00.000Z' },
])

// 获取等级类型
const getLevelType = (level: string) => {
  const types: Record<string, string> = {
    diamond: '',
    gold: 'warning',
    silver: 'info',
    bronze: 'success',
  }
  return types[level] || 'info'
}

// 初始化客户增长图表
const initCustomerGrowthChart = () => {
  if (!customerGrowthChart.value) return

  customerGrowthChartInstance = echarts.init(customerGrowthChart.value)

  // 根据时间周期生成数据
  const trendData = generateGrowthTrendData()

  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['新增客户', '累计客户'],
    },
    xAxis: {
      type: 'category',
      data: trendData.xAxisData,
    },
    yAxis: [
      {
        type: 'value',
        name: '新增客户',
        position: 'left',
      },
      {
        type: 'value',
        name: '累计客户',
        position: 'right',
      },
    ],
    series: [
      {
        name: '新增客户',
        type: 'bar',
        yAxisIndex: 0,
        data: trendData.newCustomers,
        itemStyle: {
          color: '#409EFF',
        },
      },
      {
        name: '累计客户',
        type: 'line',
        yAxisIndex: 1,
        data: trendData.totalCustomers,
        smooth: true,
        itemStyle: {
          color: '#67C23A',
        },
      },
    ],
  }

  customerGrowthChartInstance.setOption(option)
}

// 初始化客户等级图表
const initCustomerLevelChart = () => {
  if (!customerLevelChart.value) return

  customerLevelChartInstance = echarts.init(customerLevelChart.value)

  // 生成客户等级数据
  const levelData = generateLevelData()

  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '客户等级',
        type: 'pie',
        radius: '50%',
        data: levelData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }

  customerLevelChartInstance.setOption(option)
}

// 初始化客户活跃度图表
const initCustomerActivityChart = () => {
  if (!customerActivityChart.value) return

  customerActivityChartInstance = echarts.init(customerActivityChart.value)

  // 生成客户活跃度数据
  const activityData = generateActivityData()

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: activityData.categories,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '客户数量',
        type: 'bar',
        data: activityData.values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' },
          ]),
        },
      },
    ],
  }

  customerActivityChartInstance.setOption(option)
}

// 初始化客户价值图表
const initCustomerValueChart = () => {
  if (!customerValueChart.value) return

  customerValueChartInstance = echarts.init(customerValueChart.value)

  // 生成客户价值数据
  const valueData = generateValueData()

  const option = {
    tooltip: {
      trigger: 'item',
    },
    series: [
      {
        name: '客户价值',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: valueData,
      },
    ],
  }

  customerValueChartInstance.setOption(option)
}

// 初始化客户地区分布图表
const initCustomerMapChart = () => {
  if (!customerMapChart.value) return

  customerMapChartInstance = echarts.init(customerMapChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
    },
    visualMap: {
      min: 0,
      max: 500,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
    },
    series: [
      {
        name: '客户数量',
        type: 'map',
        map: 'china',
        roam: false,
        label: {
          show: true,
        },
        data: [
          { name: '北京', value: 177 },
          { name: '天津', value: 42 },
          { name: '河北', value: 102 },
          { name: '山西', value: 81 },
          { name: '内蒙古', value: 47 },
          { name: '辽宁', value: 67 },
          { name: '吉林', value: 82 },
          { name: '黑龙江', value: 123 },
          { name: '上海', value: 234 },
          { name: '江苏', value: 456 },
          { name: '浙江', value: 345 },
          { name: '安徽', value: 178 },
          { name: '福建', value: 156 },
          { name: '江西', value: 134 },
          { name: '山东', value: 289 },
          { name: '河南', value: 267 },
          { name: '湖北', value: 189 },
          { name: '湖南', value: 198 },
          { name: '广东', value: 567 },
          { name: '广西', value: 123 },
          { name: '海南', value: 45 },
          { name: '重庆', value: 89 },
          { name: '四川', value: 234 },
          { name: '贵州', value: 67 },
          { name: '云南', value: 98 },
          { name: '西藏', value: 12 },
          { name: '陕西', value: 145 },
          { name: '甘肃', value: 56 },
          { name: '青海', value: 23 },
          { name: '宁夏', value: 34 },
          { name: '新疆', value: 78 },
        ],
      },
    ],
  }

  customerMapChartInstance.setOption(option)
}

// 监听增长周期变化
watch(growthPeriod, () => {
  // 这里可以根据选择的周期更新数据
  console.log('更新客户增长趋势:', growthPeriod.value)
  updateCharts()
})

// 窗口大小变化时重新调整图表
const handleResize = () => {
  customerGrowthChartInstance?.resize()
  customerLevelChartInstance?.resize()
  customerActivityChartInstance?.resize()
  customerValueChartInstance?.resize()
  customerMapChartInstance?.resize()
}

onMounted(async () => {
  await nextTick()

  // 初始化所有图表
  initCustomerGrowthChart()
  initCustomerLevelChart()
  initCustomerActivityChart()
  initCustomerValueChart()
  initCustomerMapChart()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.customer-analytics {
  padding: 0;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.card-trend {
  font-size: 11px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.card-trend.positive {
  color: #67c23a;
}

.card-trend.negative {
  color: #f56c6c;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.data-section {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-card {
    margin-bottom: 16px;
  }

  .card-content {
    flex-direction: column;
    text-align: center;
  }

  .card-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .chart-container {
    height: 250px;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>
